var sort = 0,
    num = 0,
    actIndex = '',
    page = 0;

$(function () {
    doList();
    doAjax();
})

function doList() {
    $.ajax({
        url: '/seckillGoodsC/timeSession.json',
        dataType: 'json',
        data: {
            sort: sort,
            companyCode: getItem('companyCode')
        },
        success: function (data) {
            if (data.code == 1) {
                var today = parseInt(data.weekNow2);
                var requestDay = data.weekThen2;
                var thisDay = data.weekNow.split('星期')[1];
                var textTime = ['日', '一', '二', '三', '四', '五', '六'];
                //找到今天索引
                var preDay = 0;
                for(var g=0;g<textTime.length;g++){
                    if(thisDay==textTime[g]){
                        preDay = g;
                    }
                }
                //将今天之前的三天建立新数组
                var preDays = [];
                for (var i = 0; i < 3; i++) {
                    preDay--;
                    if (preDay < 0) {
                        preDay = 6;
                    }
                    preDays.push(textTime[preDay])
                }

                var d = 4;
                if(preDays.length==3){
                    preDays = preDays.reverse();
                    for(var h=0;h<3;h++){
                        d--;
                        $('<div class="swiper-slide" sort="' + (0 - (d)) + '"><div class="text"><span>周' + preDays[h] + '抢</span><span>已结束</span></div><div class="sanjiao"></div></div>').appendTo($('.swiper-wrapper'));
                    }
                }
                $('<div class="swiper-slide active" sort="0"><div class="text"><span>周' + textTime[today] + '抢</span><span>抢购中</span></div><div class="sanjiao"></div></div>').appendTo($('.swiper-wrapper'));

                var nextDay = today;
                for (var a = 0; a < 4; a++) {
                    nextDay++;
                    if (nextDay > 6) {
                        nextDay = 0;
                    }
                    $('<div class="swiper-slide" sort="' + (a + 1) + '"><div class="text"><span>周' + textTime[nextDay] + '抢</span><span>即将开始</span></div><div class="sanjiao"></div></div>').appendTo($('.swiper-wrapper'))
                }

                //滑动导航
                var mySwiper = new Swiper('#topNav', {
                    freeMode: true,
                    freeModeMomentumRatio: 0.5,
                    slidesPerView: 'auto',

                });

                swiperWidth = mySwiper.container[0].clientWidth
                maxTranslate = mySwiper.maxTranslate();
                maxWidth = -maxTranslate + swiperWidth / 2

                $(".swiper-container").on('touchstart', function (e) {
                    e.preventDefault()
                })

                swipTrans(mySwiper);

                mySwiper.on('tap', function (swiper, e) {

                    slide = swiper.slides[swiper.clickedIndex]
                    slideLeft = slide.offsetLeft
                    slideWidth = slide.clientWidth
                    slideCenter = slideLeft + slideWidth / 2
                    // 被点击slide的中心点

                    mySwiper.setWrapperTransition(300)

                    if (slideCenter < swiperWidth / 2) {

                        mySwiper.setWrapperTranslate(0)

                    } else if (slideCenter > maxWidth) {

                        mySwiper.setWrapperTranslate(maxTranslate)

                    } else {

                        nowTlanslate = slideCenter - swiperWidth / 2

                        mySwiper.setWrapperTranslate(-nowTlanslate)

                    }

                    $("#topNav  .active").removeClass('active')

                    $("#topNav .swiper-slide").eq(swiper.clickedIndex).addClass('active');
                    sort = $("#topNav .swiper-slide").eq(swiper.clickedIndex).attr('sort')
                    mui('#refreshContainer').pullRefresh().scrollTo(0, 0);//滚动到顶部
                    mui('#refreshContainer').pullRefresh().refresh(true);
                    if ($('.mui-pull-caption').html()=='上拉显示更多') {
                        $('.mui-pull-caption').html('');
                    }

                    $('.list_box').empty();
                    page = 0;
                    doAjax();

                })

                function swipTrans(swiper){
                    var f = 0;
                    $('.swiper-slide').each(function () {
                        f++;
                        if($(this).hasClass('active')){
                            actIndex = swiper.slides[f-1];

                        }
                    })
                    slide = actIndex
                    slideLeft = slide.offsetLeft
                    slideWidth = slide.clientWidth
                    slideCenter = slideLeft + slideWidth / 2
                    // 被点击slide的中心点

                    mySwiper.setWrapperTransition(300)

                    if (slideCenter < swiperWidth / 2) {

                        mySwiper.setWrapperTranslate(0)

                    } else if (slideCenter > maxWidth) {

                        mySwiper.setWrapperTranslate(maxTranslate)

                    } else {

                        nowTlanslate = slideCenter - swiperWidth / 2

                        mySwiper.setWrapperTranslate(-nowTlanslate)

                    }
                }
            }
        }
    })
}

function doAjax() {
    page++;
    $.ajax({
        url: '/seckillGoodsC/getList.json',
        dataType: 'json',
        data: {
            pageNu: page,
            sort: sort,
            companyCode: getItem('companyCode')
        },
        beforeSend:function(){
            if(page==1){
                $('<div class="loading"><img src="../phoneImg/jiazaizhong.gif"/></div>').appendTo($('.list_box'));
            }
        },
        success: function (data) {
            $('.loading').hide();
            if (data.code == 1) {
                if(page==1){
                    $('.list_box').empty();
                    if(data.datas.length==0){
                        mui('#refreshContainer').pullRefresh().disablePullupToRefresh();
                        $('<div class="kong"><img src="../phoneImg/kong.png" alt="暂无数据"></div>').appendTo($('.list_box'));
                    }
                }
                var goodsData = data.datas;
                var ifBegin = '',ifBegin2 = '';

                for(var k=0;k<goodsData.length;k++){
                    if(sort==0){
                        ifBegin='<div class="mui-progressbar mui-progressbar-in" data-progress="'+goodsData[k].percent+'" id="progess'+goodsData[k].id+'"><span></span></div><div class="num">剩余'+goodsData[k].inventory+'件</div>'
                        ifBegin2 = '马上抢'
                    }else{
                        if(sort<0){
                            ifBegin2 = '已结束'
                        }else{
                            ifBegin2 = '即将开始'
                        }
                        ifBegin='<div class="guige">'+goodsData[k].specificationName+'</div>'
                    }
                    $('<div class="item_box mui-clearfix" goodsId="'+goodsData[k].id+'">\n' +
                        '            <div class="img"><img src="'+goodsData[k].mainImg.split(',')[0]+'" alt=""></div>\n' +
                        '            <div class="goods">\n' +
                        '                <div class="title">'+goodsData[k].goodsName+'</div>\n' +
                        ifBegin+
                        '                <div class="price"><b>￥</b>'+goodsData[k].seckillPrice+' <b class="quondam">￥'+goodsData[k].salePrice+'</b></div>\n' +
                        '                <div class="buy">'+ifBegin2+'</div>\n' +
                        '            </div>\n' +
                        '        </div>').appendTo($('.list_box'))
                    if(sort==0){
                        var progressbar1 = mui('#progess'+goodsData[k].id+'');
                        var progressBar = goodsData[k].percent;
                        mui(progressbar1).progressbar().setProgress(progressBar)
                    }
                }
                mui('body').on('tap','.item_box',function () {
                    window.location.href="seckill_goods.html?goodsId="+$(this).attr('goodsId')
                })
                num = goodsData.length;
            }
        }
    })
    return num;
}

//上拉加载
mui.init({
    pullRefresh : {
        container:"#refreshContainer",//待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
        down: {
            contentdown : "下拉可以刷新",//可选，在下拉可刷新状态时，下拉刷新控件上显示的标题内容
            contentover : "释放立即刷新",//可选，在释放可刷新状态时，下拉刷新控件上显示的标题内容
            contentrefresh : "正在刷新...",//可选，正在刷新状态时，下拉刷新控件上显示的标题内容
            callback: function () {
                window.location.reload();
                mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
            }
        },
        up : {
            contentrefresh : "正在加载...",//可选，正在加载状态时，上拉加载控件上显示的标题内容
            contentnomore:'我是有底线的',//可选，请求完毕若没有更多数据时显示的提醒内容；
            callback :function(){
                setTimeout(function () {
                    var numResult;
                    numResult = doAjax();
                    if (numResult < 20) {
                        mui('#refreshContainer').pullRefresh().endPullupToRefresh(true);
                    } else {
                        mui('#refreshContainer').pullRefresh().endPullupToRefresh(false);
                    }
                }, 1000);
            } //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
        }
    }
});